package binarysearch.test33;

/**
 * 搜索旋转排序数组
 *
 * @author code_yc
 * @version 1.0
 * @date 2020/7/11 10:51
 */
public class Solution1 {

    // 两边二分查找，第一遍查找最小的元素位置，第二步搜索目标值
    public int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) return -1;
        int n = nums.length;
        int l = 0, r = n - 1;
        while (l < r) {
            int mid = l + ((r - l) >> 1);
            if (nums[mid] > nums[r]) {
                l = mid + 1;
            } else {
                r = mid;
            }
        }
        int s = l;
        l = 0;
        r = n - 1;
        while (l <= r) {
            int mid = l + ((r - l) >> 1);
            int v = (mid + s) % n;
            if (nums[v] < target) {
                l = mid + 1;
            } else if (nums[v] > target) {
                r = mid - 1;
            } else {
                return v;
            }
        }
        return -1;
    }
}
